package com.dm.wallpaper.library.fraction;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.ablility.slice.WallpaperBoardBrowserAbilitySlice;
import com.dm.wallpaper.library.database.Database;
import com.dm.wallpaper.library.items.Filter;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.utils.Log;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.service.WindowManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class WallpaperBoardBrowserSearchFraction extends Fraction implements Component.ClickedListener, Component.FocusChangedListener {
    Component component;
    TextField searchContent;
    Component tablayout;
    Component showSearchInfoLayout;
    Image rightMuneIcon;
    Text showSearchInfo;
    DirectionalLayout scrollTable;

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        component = scatter.parse(ResourceTable.Layout_fraction_wallpaper_board_browser_search, null, false);
        return component;
    }

    @Override
    protected void onActive() {
        super.onActive();
        initView();
    }

    private void initView() {
        component.findComponentById(ResourceTable.Id_left_mune_icon).setClickedListener(this);
        searchContent = (TextField) component.findComponentById(ResourceTable.Id_search_content);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(new RgbColor(0x00000000));
        searchContent.setBubbleElement(shapeElement);

        showSearchInfoLayout = component.findComponentById(ResourceTable.Id_show_search_info_layout);
        showSearchInfo = (Text) component.findComponentById(ResourceTable.Id_show_search_info);
        scrollTable = (DirectionalLayout) (component.findComponentById(ResourceTable.Id_scroll_table));
        String titleSearch = "";
        try {
            titleSearch = getFractionAbility().getResourceManager().getElement(ResourceTable.String_menu_search).getString();
        } catch (Exception e) {
        }

        searchContent.setHint(titleSearch);
        rightMuneIcon = (Image) component.findComponentById(ResourceTable.Id_right_mune_icon);
        rightMuneIcon.setClickedListener(this);
        rightMuneIcon.setVisibility(Component.HIDE);
        searchContent.setFocusChangedListener(this);
        addTextCouseListener();

        searchContent.requestFocus();
        searchContent.simulateClick();
    }

    private void addTextCouseListener() {
        try {
            Class clazz = Class.forName("ohos.agp.components.TextField$CursorChangedListener");
            Object mObj = Proxy.newProxyInstance(WallpaperBoardBrowserAbilitySlice.class.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    if (method.getName().equals("onCursorChange")) {
                        TextField textField = (TextField) objects[0];
                        String text = textField.getText();
                        text = text.replace(" ", "");
                        text = text.replace("\n", "");
                        text = text.replace("\"", "");
                        List<Wallpaper> wallpapers ;
                        if (!text.equals("")) {
                            rightMuneIcon.setVisibility(Component.VISIBLE);
                            Filter filter = new Filter();
                            filter.add(Filter.Create(Filter.Column.NAME).setQuery(text));
                            filter.add(Filter.Create(Filter.Column.AUTHOR).setQuery(text));
                            filter.add(Filter.Create(Filter.Column.CATEGORY).setQuery(text));
                            filter.add(Filter.Create(Filter.Column.ID).setQuery(text));
                            wallpapers = Database.get().getFilteredWallpapers(filter);

                            if (wallpapers.size() > 0) {
                                showSearchInfoLayout.setVisibility(Component.HIDE);
                                scrollTable.setVisibility(Component.VISIBLE);
                                addTablayout(wallpapers);
                            } else {
                                showSearchInfo.setText("No result found for \"" + text + "\"");
                                showSearchInfoLayout.setVisibility(Component.VISIBLE);
                                scrollTable.setVisibility(Component.HIDE);
                            }
                        } else {
                            rightMuneIcon.setVisibility(Component.INVISIBLE);
                            showSearchInfoLayout.setVisibility(Component.INVISIBLE);
                            scrollTable.setVisibility(Component.INVISIBLE);
                        }
                    }
                    return null;
                }
            });
            Method mMethod = searchContent.getClass().getDeclaredMethod("setCursorChangedListener", new Class[]{clazz});
            mMethod.setAccessible(true);
            mMethod.invoke(searchContent, new Object[]{mObj});
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("WallpaperBoardBrowserAbilitySlice.initView([]):74  反射报错了:" + e.getLocalizedMessage());
        }
    }

    private void addTablayout(List<Wallpaper> wallpapers) {
        if (tablayout != null) {
            scrollTable.removeComponent(tablayout);
        }
        if (wallpapers == null || wallpapers.size() == 0) {
            return;
        }
        tablayout = ContentCompentUtils.initWallpaperView(wallpapers, getFractionAbility());
        scrollTable.addComponent(tablayout);
    }


    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_left_mune_icon) {
            getFractionAbility().terminateAbility();
        } else if (component.getId() == ResourceTable.Id_right_mune_icon) {
            searchContent.setText("");
            component.setVisibility(Component.INVISIBLE);
            addTablayout(null);
            showSearchInfoLayout.setVisibility(Component.HIDE);
        }
    }

    @Override
    public void onFocusChange(Component component, boolean b) {
        Log.i("WallpaperBoardBrowserAbilitySlice.onFocusChange([component, b]):34     " + component.getId() + "          " + ResourceTable.Id_search_content + "              " + b);
        if (component.getId() == ResourceTable.Id_search_content) {
            if (b) {
                getFractionAbility().getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
            } else {
                getFractionAbility().getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_STATE_VISIBLE);
            }
        }
    }

}
